/* import React, { useRef, useState } from "react";

const Chat: React.FC = () => {
  const [text, setText] = useState("");
  const [isSending, setIsSending] = useState(false);

  const timeoutID = useRef<NodeJS.Timer>();

  function handleSend() {
    setIsSending(true);
    timeoutID.current = setTimeout(() => {
      alert("已发送");
      setIsSending(false);
    }, 3000);
  }

  function handleUndo() {
    setIsSending(false);
    clearTimeout(timeoutID.current);
  }

  return (
    <>
      <input value={text} disabled={isSending} onChange={e => setText(e.target.value)} />
      <button onClick={handleSend} disabled={isSending}>
        {isSending ? "发送中..." : "发送"}
      </button>
      {isSending && <button onClick={handleUndo}>撤销</button>}
    </>
  );
};
export default Chat; */

import React, { useState, useRef } from "react";

function Chat() {
  const [text, setText] = useState("");
  const lastestText = useRef(text);
  const timeoutRef = useRef<NodeJS.Timer>();

  function handleSend() {
    clearTimeout(timeoutRef.current);
    timeoutRef.current = setTimeout(() => {
      alert("正在发送：" + lastestText.current);
    }, 3000);
  }

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const { value } = e.target;
    setText(value);
    lastestText.current = value;
  }

  return (
    <>
      <input value={text} onChange={handleChange} />
      <button onClick={handleSend}>发送</button>
    </>
  );
}

export default Chat;
